<template>
  <div class="artCate-wrapper">
    <el-main class="main">
      <el-card class="box-card">
        <div slot="header" class="clearfix card-header">
          <span style="font-size: 14px">文章分类</span>
          <el-button
            style="float: right"
            size="small"
            type="primary"
            @click="addCate"
            >添加分类</el-button
          >
        </div>
        <el-table
          ref="cateTable"
          class="cateTable"
          :data="artCateTable"
          stripe
          border
          :header-cell-style="{ fontSize: '12px', color: '#000' }"
          style="width: 100%"
        >
          <el-table-column type="index" min-width="50" label="序号">
          </el-table-column>
          <el-table-column prop="cate_name" label="分类名称" min-width="80">
          </el-table-column>
          <el-table-column prop="cate_alias" label="分类别名" min-width="80">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button size="mini" type="primary" @click="editCate(row)"
                >修改</el-button
              >
              <el-button size="mini" type="danger" @click="delCate(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-main>
    <!-- 添加文章分类弹窗 -->
    <AddCateDialog
      :addDialogVisible.sync="addShow"
      @updateData="getCateList"
    ></AddCateDialog>
    <!-- 修改文章分类弹窗 -->
    <el-dialog
      class="editDialog"
      title="修改文章分类"
      :visible.sync="editShow"
      @close="editDialogClose"
      width="40%"
    >
      <el-form :model="editForm" :rules="rulesEditForm" ref="editRulesForm">
        <el-form-item label="分类名称" label-width="80" prop="cate_name">
          <el-input v-model="editForm.cate_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类别名" label-width="80" prop="cate_alias">
          <el-input v-model="editForm.cate_alias" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editCancel">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCateListApi, putCateApi, delCateApi } from "@/api/cate";
import AddCateDialog from "@/views/artCate/components/AddCateDialog";
export default {
  name: "artCate",
  components: { AddCateDialog },
  data() {
    let validate_cate_name = (rule, value, callback) => {
      // 非空字符校验校验---正则不熟
      const reg_cate_name = /\s+/;
      if (!value) {
        return callback(new Error("用户分类不能为空"));
      } else if (
        this.editForm.cate_name &&
        reg_cate_name.test(this.editForm.cate_name)
      ) {
        return callback(new Error("昵称必须是1-10位的非空字符"));
      } else {
        return callback();
      }
    };
    let validate_cate_alias = (rule, value, callback) => {
      const reg_cate_alias = /^[a-zA-Z0-9]{1,15}$/;
      if (!value) {
        return callback(new Error("分类别名不能为空"));
      } else if (
        this.editForm.cate_alias &&
        !reg_cate_alias.test(this.editForm.cate_alias)
      ) {
        return callback(new Error("分类别名必须是1-15位的字母数字"));
      } else {
        return callback();
      }
    };
    return {
      artCateTable: [],
      addShow: false,
      editShow: false, // 修改面板弹窗
      editForm: {
        id: "",
        cate_name: "",
        cate_alias: "",
      },
      rulesEditForm: {
        cate_name: [
          {
            required: true,
            message: "分类名称不能为空",
            trigger: ["change", "blur"],
          },
          {
            min: 1,
            max: 10,
            message: "分类名称必须是1-10位的非空字符",
            trigger: "blur",
          },
          { validator: validate_cate_name, trigger: ["blur", "change"] },
        ],
        cate_alias: [
          { required: true, message: "分类别名不能为空", trigger: "change" },
          {
            min: 1,
            max: 15,
            message: "分类别名必须是1-15位的字母数字",
            trigger: "blur",
          },
          { validator: validate_cate_alias, trigger: ["blur", "change"] },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取文章分类列表
    async getCateList() {
      const res = await getCateListApi();
      if (res.data.code === 0) {
        this.artCateTable = res.data.data;
      } else {
        this.$message.error("获取分类数据失败");
      }
    },
    // 添加文章分类按钮的回调
    addCate() {
      this.addShow = true;
    },

    // 修改文章分类按钮的回调
    editCate(row) {
      this.editShow = true;
      console.log("editCate", row);
      // 使用深拷贝
      // this.editForm = row;
      this.editForm = JSON.parse(JSON.stringify(row));
    },
    // 取消编辑
    editCancel() {
      this.$refs.editRulesForm.resetFields();
      this.editShow = false;
    },
    // 修改文章确定按钮的回调
    async editSubmit() {
      // 完成验证
      this.$refs.editRulesForm.validate(async (valid) => {
        console.log("valid---", valid);
        if (valid) {
          // 管理员不允许修改 id 为 1（最新） 和 2（科技） 的分类！
          if (this.editForm.id !== 1 && this.editForm.id !== 2) {
            console.log("this.editForm---", this.editForm);
            const res = await putCateApi(this.editForm);
            if (res.data.code === 0) {
              this.$refs.editRulesForm.resetFields();
              this.getCateList();
              this.$message.success("更新成功！");
            } else {
              this.$message.error("更新失败！");
            }
            this.editShow = false;
          } else {
            this.$message.error("管理员不允许修改这个分类！");
          }
        } else {
          console.log("error edit!!");
          return false;
        }
      });
    },
    // 关闭修改弹窗
    editDialogClose() {
      this.$refs.editRulesForm.resetFields();
      this.editShow = false;
    },

    // 删除文章分类按钮的回调
    delCate(row) {
      // this.editShow = true;
      console.log("delCate", row);
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 删除请求，管理员不允许删除 id 为 1（最新） 和 2（科技） 的分类！
          if (row.id !== 1 && row.id !== 2) {
            const res = await delCateApi({ id: row.id });
            if (res.data.code === 0) {
              this.getCateList();
              this.$message({
                type: "success",
                message: "删除分类成功！",
              });
            }
          } else {
            this.$message.error("管理员不允许删除这个分类！");
          }
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/style/main.less");
.main {
  margin-bottom: 20px;
  .card-header {
    span {
      line-height: 32px;
    }
  }
}
.cateTable {
  font-size: 12px !important;
}
</style>